using System;
using System.Web;
using System.Drawing;

namespace GoodStuff.Web.Controls
{
	/// <summary>
	/// ThumbnailHandler will return a cached
	/// thumbnail for the filename that was given
	/// by querystring. 
	/// </summary>
	/// <remarks>
	/// Caching is not yet implemented, but the overload of GetImageForRequest may do so.
	/// </remarks>
	public class ThumbnailHandler : IHttpHandler
	{
		public ThumbnailHandler()
		{
			//
			// TODO: Add constructor logic here
			//
		}
		#region IHttpHandler Members

		public void ProcessRequest(HttpContext context)
		{
			//HttpContext.Current.Cache[]

			using(Image img = this.GetImageForRequest(context))
			{
				if(img != null)
				{
					context.Response.Cache.SetMaxAge(TimeSpan.FromMinutes(5));
					context.Response.ContentType = "image/jpg";

					// cool info on rescaling: http://www.dotnet247.com/247reference/msgs/25/128742.aspx

					int maxwidth = (context.Request.QueryString["maxwidth"] == null)?100:int.Parse(context.Request.QueryString["maxwidth"]);
					int maxheight = (context.Request.QueryString["maxheight"] == null)?100:int.Parse(context.Request.QueryString["maxheight"]);

					int w = maxwidth,h = maxheight;
					if(img.Width > img.Height)
					{
						h = (maxwidth * img.Height) / img.Width;
					}
					else
					{
						w = (maxheight * img.Width) / img.Height;
					}

					using(Image thumb = img.GetThumbnailImage(w, h, new Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero))
					{
						thumb.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
					}
				}
			}
		}

		private bool ThumbnailCallback()
		{
			return false;
		}


		public bool IsReusable
		{
			get
			{
				// TODO:  Add ThumbnailHandler.IsReusable getter implementation
				return true;
			}
		}

		#endregion

		/// <summary>
		/// You may override this method to implement your own way 
		/// to decide how to get to the file extension or mimetype.
		/// </summary>
		protected virtual Image GetImageForRequest(HttpContext context)
		{
			try
			{
				return Image.FromFile(context.Server.MapPath(context.Request.QueryString["file"]));
			}
			catch
			{
				return null;
			}
		}
	}
}
